package com.dragon.user_service.aspect;

import com.dragon.user_service.Exception.BusinessException;
import com.dragon.user_service.Exception.StateCode;
import com.dragon.user_service.annotation.AuthCheck;
import com.dragon.user_service.api.RPC.permissionService;
import com.dragon.user_service.domain.Enum.UserRoleEnum;
import com.dragon.user_service.domain.entity.User;
import com.dragon.user_service.service.UserService;
import com.dragon.user_service.util.ThrowUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/*
 * 权限校验增强类-切面类
 * */
@Aspect
@Component
public class authCheckAspect {

    @Resource
    private UserService userService;
    @Resource
    private permissionService permissionService;

    @Around("@annotation(authCheck)")
    public Object doCheck(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
//        如果该接口不需要权限，直接放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        String userRoleCode = permissionService.getUserRoleCode(loginUser.getUser_id());
//        如果该接口需要权限，先判空
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRoleCode);
        ThrowUtil.throwIf(userRoleEnum == null, StateCode.PARAMS_ERROR);
//        如果是超管,那通行
        if(userRoleEnum.equals(UserRoleEnum.SUPER_ADMIN)){
            joinPoint.proceed();
        }
        //如果是管理员用户,但是该接口超管专属,无权限
        if(userRoleEnum.equals(UserRoleEnum.ADMIN)&&mustRoleEnum.equals(UserRoleEnum.SUPER_ADMIN)){
            throw new BusinessException(StateCode.NO_AUTH_ERROR,"无权限操作该用户");
        }
        //如果是普通用户,但是操作非普通用户,无权限
        if(userRoleEnum.equals(UserRoleEnum.User)&&!mustRoleEnum.equals(UserRoleEnum.User)){
            throw new BusinessException(StateCode.NO_AUTH_ERROR,"无权限操作该用户");
        }
//        这里暂时用户只有普通用户和管理员两种角色，今后如果要新增角色，便于扩展
        return joinPoint.proceed();

    }
}
